package com.yunhe.authority.controller.company;

import com.yunhe.authority.domain.authority.User;
import com.yunhe.authority.domain.company.Employee;
import com.yunhe.authority.service.company.EmployeeService;
import com.yunhe.authority.util.MyHeaderUtil;
import com.yunhe.common.annotation.OperationRecord;
import com.yunhe.common.constant.SystemConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.model.ResultObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author forgottener
 */
@Api(value = "employees", description = "员工管理", tags = {"Authority_Employee"})
@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private EmployeeService employeeService;

    /**
     * 根据企业获得员工列表
     * @param companyId
     * @param roleType
     * @param pageParam
     * @return
     */
    @ApiOperation("根据条件获得企业员工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "roleType", value = "角色名称", dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/getEmployeeByCondition",method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getEmployeeByCondition(
            @RequestParam(value = "companyId",required = false) Long companyId,
            @RequestParam(value = "roleType",required = false)  String roleType,
            @ModelAttribute PageParam pageParam) throws ArgumentErrorException {
        Iterable<Employee> results = employeeService.getEmployeeByCondition(companyId, roleType, pageParam);
        return new ResponseEntity<>(new ResultObject<>(results), HttpStatus.OK);
    }

    @ApiOperation("添加用户")
    @RequestMapping(method = RequestMethod.POST)
    @OperationRecord(menu = "员工管理", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> post(@RequestParam(value = "companyId") Long companyId,
                                             @RequestParam(value = "roleIds") String roleIds,
                                             @RequestBody Employee employee)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        User headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser != null) {
            employee.setCreator(headerUser.getTitle());
        }
        Employee newEmployee = employeeService.createEmployee(employee, companyId, roleIds);
        return new ResponseEntity<>(new ResultObject<>(newEmployee), HttpStatus.OK);
    }

    @ApiOperation("根据员工ID获得员工详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<ResultObject<Employee>> get(@PathVariable("id") Long id) {
        Employee employee = employeeService.findByEmployeeId(id);
        return new ResponseEntity<>(new ResultObject<>(employee), HttpStatus.OK);
    }

    @ApiOperation("更新员工（更新全部字段）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @OperationRecord(menu = "员工管理", actionType = SystemConsts.ACTION.EDIT)
    public ResponseEntity<ResultObject> put(@PathVariable("id") Long id,
                                            @RequestParam(value = "companyId") Long companyId,
                                            @RequestParam(value = "roleIds",required = true) List<Long> roleIds,
                                            @RequestBody Employee employee) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        employee.setId(id);
        employeeService.updateEmployee(employee, companyId, roleIds);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    @ApiOperation("根据员工ID删除员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "员工IDs", required = true, dataType = "String", paramType = "path")
    })
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @OperationRecord(menu = "员工管理", actionType = SystemConsts.ACTION.DELETE)
    public ResponseEntity<ResultObject> delete(@PathVariable("ids") String ids) throws ArgumentErrorException {
        employeeService.deleteEmployee(ids);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    @ApiOperation("重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "用户IDs", required = true, dataType = "String", paramType = "path")
    })
    @RequestMapping(value = "/resetPassword/{ids}", method = RequestMethod.PUT)
    @OperationRecord(menu = "员工管理", actionType = SystemConsts.ACTION.EDIT)
    public ResponseEntity<ResultObject> resetPassword(@PathVariable("ids") String ids) throws ArgumentErrorException {
        List<Employee> employees = employeeService.resetPassword(ids);
        return new ResponseEntity<>(new ResultObject<>(employees), HttpStatus.OK);
    }

    @ApiOperation("禁用/恢复员工账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "用户id ", dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "activity", value = "状态 ", dataType = "string", paramType = "query",example =  "1 正常  0  禁用"),
    })
    @RequestMapping(value = "/{ids}",method = RequestMethod.PATCH)
    public ResponseEntity<ResultObject> disableRecoveryUser (@PathVariable("ids") String ids ,
                                                             @RequestParam(value = "activity") String activity) throws ArgumentErrorException {
        User headerUser = myHeaderUtil.getHeaderUser();
        employeeService.disableRecoveryEmployee(ids, activity, headerUser);
        return new ResponseEntity<>(new ResultObject<>(), HttpStatus.OK);
    }

    /**
     * 根据企业ID与角色ID获得用户列表(分页)
     * @param roleId 角色ID
     * @param companyId 企业id
     * @param keywords 关键词
     */
    @ApiOperation("根据企业ID与角色ID获得用户列表(分页)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "企业id", required = true, dataType = "long", paramType = "query"),
    })
    @RequestMapping(value = "/findEmployeesByIdAndStationIdOrFirmId", method = RequestMethod.GET)
    public ResultObject<Page<Employee>> findUsersByIdAndStationIdOrFirmId(@RequestParam(value = "roleId", required = true) Long roleId,
                                                                          @RequestParam(value = "companyId", required = true) Long companyId,
                                                                          @RequestParam(value = "keywords", required = false) String keywords,
                                                                          @ModelAttribute PageParam pageParam) {
        Page<Employee> users = employeeService.getEmployeesByCompanyIdAndRoleId(companyId, roleId, keywords ,pageParam);
        return new ResultObject<>(users);
    }

    @ApiOperation("移除员工与企业角色的关系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "employeeId", value = "员工ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "long", paramType = "query")
    })
    @RequestMapping(value = "/employeeUnbindCompanyRole", method = RequestMethod.GET)
    public ResultObject employeeUnbindCompanyRole(@RequestParam(value = "employeeId", required = true) Long employeeId,
                                                  @RequestParam(value = "roleId", required = true) Long roleId) {
        employeeService.employeeUnbindCompanyRole(employeeId, roleId);
        return new ResultObject<>("success");
    }
}
